package cn.jsu.oj.judgment.net.starter;


import cn.jsu.oj.judgment.config.ResourceConfig;
import cn.jsu.oj.judgment.net.JudgeWriteClient;
import cn.jsu.oj.judgment.parsing.JudgeStarterAnn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


/**
 * 判题机结果写回 连接启动器
 */
@Slf4j
@Component("JudgeWriteActiveStarter")
@JudgeStarterAnn(starter = 101)
public class JudgeWriteActiveStarter implements JudgeStarter{

    @Autowired
    JudgeWriteClient judgeWriteClient;


    @Autowired
    ScheduledThreadPoolExecutor judgeSchedule;

    private static final Integer JUDGE_ACTIVE_SLEEP = ResourceConfig.getConfigInteger("net.judge.active.sleep");

    private boolean isRun = false;


    private ScheduledFuture<?> scheduledFuture;

    @Override
    public void start() {
        if(this.isRun){
            return;
        }
        this.isRun = true;

        this.scheduledFuture =judgeSchedule.scheduleAtFixedRate(() -> {
            if (!ServiceStarter.judgeWriteActiveSign ) {
                log.info("----------正在连接结果写回......");
                judgeWriteClient.start();
            }
            else {
                log.info("----------连接结果写回成功............");
                judgeSchedule.setRemoveOnCancelPolicy(true);
                Objects.requireNonNull(this.scheduledFuture
                        , "----------判题机调度未来为空，任务中断失败......")
                        .cancel(true);
                this.isRun = false;
            }
        }, 0, JUDGE_ACTIVE_SLEEP, TimeUnit.MILLISECONDS);

    }
}
